package com.icangya.DAO.impl;

import com.icangya.DAO.IGiftAdvertMoneyDAO;
import com.icangya.domain.GiftAdvertMoney;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Repository
public class GiftAdvertMoneyDAOImpl  extends  BaseDAO<GiftAdvertMoney> implements IGiftAdvertMoneyDAO{

    Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public GiftAdvertMoney getGiftAdvertMoneyByOpenId(String openId) {

        String hql="FROM GiftAdvertMoney gm where gm.openId=?";
        List<GiftAdvertMoney> list= (List<GiftAdvertMoney>) getHibernateTemplate().find(hql,openId);

        if(list.size()>0)
            return list.get(0);
        return null;
    }

    @Override
    public int updateGiftAdvertMoney(String openId, double money) {

       int result= getHibernateTemplate().execute(new HibernateCallback<Integer>() {
           @Override
           public Integer doInHibernate(Session session) throws HibernateException {
               String hql="update GiftAdvertMoney gm set gm.gitAdvertMoney=gm.gitAdvertMoney+?,gm.modifiedTime=? where gm.openId=? ";
              Query query= session.createQuery(hql);
              query.setParameter(0,money);
              query.setParameter(1,new Timestamp(new Date().getTime()));
              query.setParameter(2,openId);

               int ret=  query.executeUpdate();

               return ret;
           }
       });

        return result;
    }

    @Override
    public List getAllGitAdvertMoney() {

        String hql="FROM GiftAdvertMoney ";
        List<GiftAdvertMoney> list= (List<GiftAdvertMoney>) getHibernateTemplate().find(hql);
        if(list.size()>0)
            return list;
        return null;
    }
}


